<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Chqians;
use think\Db;
/**
 * 设计更改单
 *
 * @icon fa fa-circle-o
 */
class Sjchange extends Backend
{

    /**
     * Sjchange模型对象
     * @var \app\admin\model\Sjchange
     */
    protected $model = null;

    // protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['shengh'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Sjchange;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()

    {
        
        $this->relationSearch= true;
        $this->searchFields="fname";
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);      
       
        
        // halt($this->auth->id);
        $ids=Chqians::where('user_id',$this->auth->id)->column('chang_id');
       
        // halt($ids);
      
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $list = $this->model
                    // ->alias('a')
                    // ->join('fa_admin b','a.admin_ids=b.id')
                    // ->with(['admin'])
                    ->where($where)
                    ->where("id",'in',$ids)                 
                    ->order($sort, $order)
                    ->paginate($limit);
                // $pss=$this->model->where($where_str)->select();
        //   halt($list);
            foreach ($list as $key=>$row) {
                
                $arrs=explode(',',$row["admin_ids"]);
                $ps=[];
                foreach($arrs as $k=>$v){
                    $rs=Db::table("fa_admin")->where("id",$v)->find();
                    array_push($ps,$rs["nickname"]);
                }
                $row["admin_ids"]=implode(',',$ps);
                $qians=Db::table("fa_chqians")->where("user_id",$this->auth->id)->where("chang_id",$row["id"])->find();
                // halt($qians["status"]);
                
           
                // halt($va);
                $list[$key]["status55"]= $qians;
                // // $list[$key]["status"]='已签收2';
                // if(!in_array($row["id"],$ids) && $this->auth->id!=1){
                //     unset($list[$key]);
               
                // }
                // $list = collection($list)->toArray();
                // halt($list);
                $row->visible(['id','fname','fpath_files','fbecause','admin_ids','status','createtime','status55']);
                $row->visible(['admin']);
				// $row->getRelation('admin')->visible(['nickname']);
            }
            if($this->auth->id!=1){
              
                $result = array("total" => $list->total(), "rows" => $list->items()); 
            //    $pp= json_encode($result,true);
            //    $ps=json_decode($pp,true);
            // //    halt($ps);
            // $arr=array_values($ps);
            //     $ps=array("total"=>7,"rows"=>$arr);
                return json($result);
            }else{
                $result = array("total" => $list->total(), "rows" => $list->items());
                return json($result);
                
            }
            

          
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            // halt(pathinfo($params["fpath_files"]));
            $n=pathinfo($params["fpath_files"]);
            // halt($n["filename"]);
            $pp=explode("@",$n["filename"]);

            // $params["fname"]=$n["filename"];
            $params["fname"]=$pp[1];
            $params["admin_ids"]=$params["admin_ids"].',1';
            $result = $this->model->allowField(true)->save($params);
            // halt($this->model->id);
            $ap=explode(',',$params["admin_ids"]);
            foreach($ap as $k=>$v){
                $arr["chang_id"]= $this->model->id;
                $arr["user_id"]=$v;
                $arr["status"]=0;
                (new Chqians())->save($arr);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    public function shengh($ids=null){

        $row = $this->model->get($ids);
        $row=json_decode($row,true);
        // halt($row);
        $rs=Db::table("fa_chqians")->where("chang_id",$row["id"])->where("user_id",$this->auth->id)->find();
        $rss=Db::table("fa_chqians")->where("id",$rs["id"])->update([
            "status"=>1
        ]);
        if($rss){
            $this->success("审核成功",'Sjchange/index');
        }else{
            $this->error("审核失败",'Sjchange/index');
        }
    }

}
